<template>
  <div class="com-container">
    <div class="com-chart" ref="popularcourse"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: "PopularCourse",
  data() {
    return {
      mychart: null,
      allData: null, //服务器返回的数据
      currentPage: 1, //当前显示的页数
      totalPage: 0, //一共有多少页
      timeId: null, //定时器标识
    };
  },
  created() {
    //在组件创建完成之后进行回调函数的注册
    this.$socket.registerCallBack('popularData',this.getData)
  },
  mounted() {
    this.initChart();
    //this.getData();
    //发送数据给服务器，对服务器请求数据
    this.$socket.send({
      action: 'getData',
      socketType: 'popularData',
      chartName: 'popular_course',
      value: ''
    })
    //启动定时器
    this.startInterval();
    window.addEventListener("resize", this.screenAdapter);
    //在页面加载完成的时候，主动进行屏幕的适配
    this.screenAdapter()
  },
  destroyed() {
    clearInterval(this.timeId);
    window.removeEventListener('resize',this.screenAdapter)
    //在组件销毁之后进行回调函数的取消
    this.$socket.unRegisterCallBack('popularData')
  },
  methods: {
    initChart() {
      this.mychart = this.$echarts.init(this.$refs.popularcourse, this.theme);
      //对图表初始化配置的控制
      const initOption = {
        title: {
          text: "▎最受欢迎前十课程",
          left: 20,
          top: 20,
        },
        grid: {
          top: "20%",
          left: "3%",
          right: "6%",
          bottom: "10%",
          containLabel: true, //距离是包含坐标轴上的文字
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "line",
            z: 0,
            lineStyle: {
              color: "rgb(49, 63, 80)",
            },
          },
        },
        xAxis: {
          type: "value",
        },
        yAxis: {
          type: "category",
        },
        series: [
          {
            type: "bar",
            label: {
              show: true,
              position: "right",
              textStyle: {
                color: "white",
              },
            },
            itemStyle: {
              color: new this.$echarts.graphic.LinearGradient(0, 0, 1, 0, [
                {
                  offset: 0,
                  color: "#5052EE",
                },
                {
                  offset: 1,
                  color: "#AB6EE5",
                },
              ]),
            },
          },
        ],
      };
      this.mychart.setOption(initOption);

      //对图表对象进行鼠标事件的监听
      this.mychart.on("mouseover", () => {
        clearInterval(this.timeId);
      });
      this.mychart.on("mouseout", () => {
        this.startInterval();
      });
    },
    getData(ret) {
      //const { data: ret } = await this.$http.get("popular_course");
      console.log(ret, "popular_course");
      this.allData = ret;
      //对数组进行排序
      this.allData.sort((a, b) => {
        return a.value - b.value;
      });
      //每5个元素显示一页
      this.totalPage =
        this.allData.length % 5 === 0
          ? this.allData.length / 5
          : this.allData.length / 5 + 1;
      this.updateChart();
    },
    updateChart() {
      const start = (this.currentPage - 1) * 5;
      const end = this.currentPage * 5;
      const showData = this.allData.slice(start, end);
      const xdata = showData.map((item) => {
        return item.choice_counts;
      });
      const ydata = showData.map((item) => {
        return item.course_id;
      });
      const dataOption = {
        yAxis: { data: ydata },
        series: [{ data: xdata }],
      };
      this.mychart.setOption(dataOption);
    },
    startInterval() {
      if (this.timeId) {
        clearInterval(this.timeId);
      }
      this.timeId = setInterval(() => {
        this.currentPage++;
        if (this.currentPage > this.totalPage) {
          this.currentPage = 1;
        }
        this.updateChart();
      }, 3000);
    },
    //当浏览器的大小发生变化时，调用该方法，完成屏幕的适配
    screenAdapter() {
      const titleFontSize = (this.$refs.popularcourse.offsetWidth / 100) * 3.6;
      const adapterOption = {
        title: {
          textStyle: { fontSize: titleFontSize },
        },
        tooltip: {
          axisPointer: {
            lineStyle: { width: titleFontSize },
          },
        },
        series: [
          {
            barWidth: titleFontSize,
            itemStyle: {
              barBorderRadius: [0, titleFontSize / 2, titleFontSize / 2, 0],
            },
          },
        ],
      };
      this.mychart.setOption(adapterOption);
      //手动调用图表对象的resize
      this.mychart.resize();
    },
  },
  computed: {
    ...mapState(['theme'])
  },
  watch: {
    theme() {
      this.mychart.dispose()//销毁当前图表
      this.initChart()//重新以最新主题初始化图表对象
      this.screenAdapter()
      this.updateChart()
    }
  },
};
</script>

<style>
</style>